﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MethodWorx.CMS.Services;
using System.Xml.Serialization;
using MethodWorx.CMS.Content;
using System.IO;
using MethodWorx.Core.Serialization;
using System.Xml;
using MethodWorx.Core.DomainModel;

namespace MethodWorx.CMS.Plugins.StarterTemplates
{
    public class StarterTemplatesController : Controller
    {
        protected IdeExtension extension;
        protected PluginService service;
        protected SchemaService schema;
        protected IRepositoryRegistry repositories;
        /// <summary>
        /// Required constructor, must have an "extension" argument
        /// and any other arguments the dependency injection contain knows about
        /// </summary>
        /// <param name="extension"></param>
        /// <param name="service"></param>
        public StarterTemplatesController(IdeExtension extension, PluginService service, SchemaService schema, IRepositoryRegistry repositories)
        {
            this.extension = extension;
            this.service = service;
            this.schema = schema;
            this.repositories = repositories;
        }


        /// <summary>
        /// Invoke method, default action for the post
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="submit"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Invoke()
        {
            return new EmbeddedViewResult(this.extension.WebEditor, null);
        }

        /// <summary>
        /// Invoke method, default action for the post
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="submit"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload()
        {
            var serializer = new AggregateXmlSerializer();
            using (XmlTextReader reader = new XmlTextReader(HttpContext.Request.Files["file"].InputStream))
            {
               /* serializer.Deserialize(new Type[]
                {
                    typeof(PageTemplate)
                }, repositories, reader);*/
            }
            return new EmbeddedViewResult(this.extension.WebEditor, null);
        }

        [HttpGet]
        public ActionResult Export()
        {
            return File(UTF8Encoding.UTF8.GetBytes(this.schema.SerializeToXml()), "text/xml", "startertemplate.xml");
        }
    }
}
